// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import DTTS from "../../dddd/DTTS";
import YP from "../../sound/music";
import AnimalManager from "../Manager/AnimalManager";
import BUIManager from "../Manager/BUIManager";
import GeZiManager from "../Manager/GeZiManager";
import TNanager from "../Manager/TNanager";
import ZManager from "../Manager/ZManager";
import GMessage from "./GMessage";
import MessageCenter from "./MessageCenter";
import { SHMessage } from "./SHMessage";

const {ccclass, property} = cc._decorator;
export enum MsgId{
    CreateRoom=0,
    ConnectRoom=1,
}



export interface GetAllLocationRes
{id:MsgId;
error:ErrorCode;
alllocation:[];}
export interface ChangeLocationRes
{id:MsgId;
error:ErrorCode;
playername:string;
nextlocation:number;
nowlocation:number;
value:number;}
export enum ErrorCode{
    WebSocketErr=0,
    WebSocketSuccess=1,
    PlayerNameEmpty=2,
    CreateRoomSuccess=3,
    CreateRoomFail=4,
    ConnectRoomSuccess=5,
    PasswordORRoomnameErr=6,
    ChangeLocationSuccess=7,
    ChangeLocationFail=8,
    GetAllLocationSuccess=9,
    GetAllLocationFail=10,
    GameStartSuccess=11,
    GameStartNotAtRoomFail=12,
    GameStartNotOwnerFail=13}

export interface CreateRoomReq {
    roomname: string;  // 房间名称
    password: string;  // 房间密码（可选，取决于您的需求）
}

export interface CreateRoomRes
{
    error:ErrorCode;
}

export interface ConnectRoomReq{
    roomname:string;
    password:string;
}

export interface ConnectRoomRes
{
    error:ErrorCode;
}
@ccclass
export default class KHD2 extends cc.Component {
    static Client:any=null;
    static Gammer:any=null;
static n="qjc"
static c=0
static ln:number=0;
static dn:number=0;
static   socket:any=null
static JMessage= []; 
static PT:number[]=[0];//玩家序号，0为观战席
static xz:number=0
static FZ:boolean=false;//是否为房主
static WZ:cc.Node=null;
static FJN:boolean=true;
static id:number//唯一id
static juese:number[]=[];
static HB:number[]=[0,0,0];
static Cname:string="213";//用户名
//118.25.16.45:3001/
static ingame:number=0;
  static dat: any;

        
protected onLoad(): void {
    
}



         start(): void {
            //  KHD2.Cname=Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000+""
          KHD2.socket = new WebSocket("ws://119.29.174.60:80")
          const data = {
            id: 9,
           playername: KHD2.Cname
        };
       
        KHD2.socket.onopen=function(event) {
            KHD2.socket.send(JSON.stringify(data))}

      
      
        //  KHD2.socket
       //   KHD2.socket.onopen = function(event) {
        //        console.log('WebSocket connection established');
        //    };
            
            // 监听 WebSocket 错误事件
         //   KHD2.socket.onerror = function(error) {
          //      console.error('WebSocket error: ' + error);
          //  };
            
            // 监听 WebSocket 消息事件
            KHD2.socket.onmessage = function(event) {
                console.log('Message from server ',event.data);
                let k=JSON.parse(event.data)
              //  console.log(event.data.id);
                console.log(k.id);
                switch (k.id) {
                    case 0:KHD2.BcreatRoom(k.error,k.roomname)
                        
                        break;
                        case 1:KHD2.BConnectRoom(k.error,k.roomname)
                        
                        break;

                        case 2:KHD2.ALLpeaple(k)
                        
                        break;

                        case 3:KHD2.BGETA(k)
                        
                        break;
                        case 4:KHD2.redtos(k)
                        
                        break;

                        case 5:KHD2.GM(k)
                        
                        break;
                        case 6:KHD2.BGload(k)
                        
                        break;
                        case 7:KHD2.FJG(k)
                        
                        break;
                        case 8:KHD2.GFJ(k)
                        
                        break;
                       
                    default:
                        break;
                }
            };
            
            // 监听 WebSocket 连接关闭事件
            KHD2.socket.onclose = function(event) {
                console.log('WebSocket connection closed');
            };

        }


static creatRoom(FJname:string,PassW:string){
    const data = {
        id: MsgId.CreateRoom,
        roomname:FJname,
    password:PassW,
    };
   
   
   
    KHD2.socket.send(JSON.stringify(data))
  // KHD2.Client.on('createroomTF',(data:any)=>{
//switch (data) {
   // case 'T':KHD2.FZ=true;KHD2.inRoom(FJname,PassW);  
        
     //   break;
     //   case 'F':cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("创建房间失败");
    // /   
       // break;

  //  default:
      //  break;
//}
  //})
   
 // }





    
}
static BcreatRoom(error:number,FJname:string){

   
   
   if (error==3) {
    KHD2.FZ=true
  KHD2.BConnectRoom(5,FJname)
   }

   if (error==4) {
    cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("创建房间失败");
   }




}
   
  





    


static ConnectRoom(FJname:string,PassW:string){
    const data = {
        id: MsgId.ConnectRoom,
        roomname:FJname,
    password:PassW,
    };
   
   
   
    KHD2.socket.send(JSON.stringify(data))
  // KHD2.Client.on('createroomTF',(data:any)=>{
//switch (data) {
   // case 'T':KHD2.FZ=true;KHD2.inRoom(FJname,PassW);  
        
     //   break;
     //   case 'F':cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("创建房间失败");
    // /   
       // break;

  //  default:
      //  break;
//}
  //})
   
 // }





    
}




static BConnectRoom(error:number,FJname:string){
   console.log() 
    
    cc.find("Canvas/New Node/New Label").getComponent(cc.Label).string=FJname
   
   
   
    switch (error) {
        case  4: cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("房间号或密码错误");
            
            break;
           
          
            case  5:
if (cc.find("Canvas/fangJian/p1")) {
    cc.find("Canvas/fangJian/p1").getComponent(YP).PauseAudioclip("byp",0)
    setTimeout(()=>{   cc.find("Canvas/fangJian/p1").getComponent(YP).stopAllAudio();
     cc.find("Canvas/fangJian/p1").getComponent(YP).PlayAudioclip("byp",true,1)},3200) 
}

         
     
    
        cc.find("Canvas/CHU").active=false;
        //房间重连
        const data = {
            id:2,
            error:0,
            playername:KHD2.Cname,
            nextlocation:0,
            nowlocation:0,
            value:0,
          
          };
        
  
        
        
        KHD2.socket.send(JSON.stringify(data)) 

    
        KHD2.GETA()
    
    
    
    
    }





}

static GETA(){

    const data = {
        id:3,
        error:0,
        playername:KHD2.Cname,
       
      
      };
    
    
    
    
    KHD2.socket.send(JSON.stringify(data)) 






}










static BGETA(data){
  
    KHD2.c=0
    
    console.log(data.alllocation)
    let n
       for(let oo of data.alllocation){
        let a=[oo.playername,oo.nextlocation,oo.nowlocation,oo.value]

        //    if (a[2]!=0) {
         //       cc.find("Canvas/fangJian").children[a[2]].getComponent(DTTS).LK();
          //     } 
            
             //   if (a[2]==7) {
                //    cc.find("Canvas/fangJian").children[1].getComponent(DTTS).LK();
             //  cc.find("Canvas/fangJian").children[3].getComponent(DTTS).LK();
             //  cc.find("Canvas/fangJian").children[5].getComponent(DTTS).LK();
              //  }
              //  if (a[2]==8) {
              //      cc.find("Canvas/fangJian").children[2].getComponent(DTTS).LK();
             //   cc.find("Canvas/fangJian").children[4].getComponent(DTTS).LK();
             //   cc.find("Canvas/fangJian").children[6].getComponent(DTTS).LK();
              //  }
      
      
      
      
      
      
            if (a[1]!=0&&a[1]<7) {
        cc.find("Canvas/fangJian").children[a[1]].getComponent(DTTS).BC(a[0]);
    
    } 
    
        if (a[1]==7) {
            cc.find("Canvas/fangJian").children[1].getComponent(DTTS).BC(a[0])
       cc.find("Canvas/fangJian").children[3].getComponent(DTTS).BC(a[0])
       cc.find("Canvas/fangJian").children[5].getComponent(DTTS).BC(a[0])
    
        }
        if (a[1]==8) {
            cc.find("Canvas/fangJian").children[2].getComponent(DTTS).BC(a[0])
        cc.find("Canvas/fangJian").children[4].getComponent(DTTS).BC(a[0])
        cc.find("Canvas/fangJian").children[6].getComponent(DTTS).BC(a[0])
  
        }
    


KHD2.c+=a[3]


    
    }
    
 
    console.log(KHD2.c)
    //}
    this.FJN=true;
    for(let a of data){
        if(a[1]==0){this.FJN=false;break;}
            }
    
            console.log(this.FJN)
    if(KHD2.c==6&&this.FJN &&this.FZ){ cc.find('Canvas/fangJian/kaishi').active=true
    }
    console.log(data)
       }





static ALLpeaple(data){
let a=[data.playername,data.nextlocation,data.nowlocation,data.value]




    //for(let a of data){
        if (a[2]!=0) {
            cc.find("Canvas/fangJian").children[a[2]].getComponent(DTTS).LK();
           } 
        
            if (a[2]==7) {
                cc.find("Canvas/fangJian").children[1].getComponent(DTTS).LK();
           cc.find("Canvas/fangJian").children[3].getComponent(DTTS).LK();
           cc.find("Canvas/fangJian").children[5].getComponent(DTTS).LK();
            }
            if (a[2]==8) {
                cc.find("Canvas/fangJian").children[2].getComponent(DTTS).LK();
            cc.find("Canvas/fangJian").children[4].getComponent(DTTS).LK();
            cc.find("Canvas/fangJian").children[6].getComponent(DTTS).LK();
            }
  
  
  
  
  
  
        if (a[1]!=0) {
    cc.find("Canvas/fangJian").children[a[1]].getComponent(DTTS).BC(a[0]);
   } 

    if (a[1]==7) {
        cc.find("Canvas/fangJian").children[1].getComponent(DTTS).BC(a[0])
   cc.find("Canvas/fangJian").children[3].getComponent(DTTS).BC(a[0])
   cc.find("Canvas/fangJian").children[5].getComponent(DTTS).BC(a[0])
    }
    if (a[1]==8) {
        cc.find("Canvas/fangJian").children[2].getComponent(DTTS).BC(a[0])
    cc.find("Canvas/fangJian").children[4].getComponent(DTTS).BC(a[0])
    cc.find("Canvas/fangJian").children[6].getComponent(DTTS).BC(a[0])
    }


   

KHD2.c+=a[3]
console.log(KHD2.c)
//}
this.FJN=true;
for(let a of data){
    if(a[1]==0){this.FJN=false;break;}
        }

        console.log(this.FJN)
if(KHD2.c==6&&this.FJN &&this.FZ){ cc.find('Canvas/fangJian/kaishi').active=true
}
console.log(data)
   }




static Gamemessa(){}

static BPstart(data){
    let c=JSON.parse(data);
        
        KHD2.JMessage.push(c)
        for(let v of KHD2.JMessage){
           if(v[0]==KHD2.dn+1){
            
            KHD2.dn++
        
        let a=new GMessage(v[1].Type,v[1].Command,v[1].Content,v[1].from,v[1].SHtype)
        
        console.log(data)
        MessageCenter.SendMessage(a)
            KHD2.JMessage.splice(KHD2.JMessage.indexOf(v),1);
           } 
        
        }
        
        
        KHD2.ln=KHD2.dn;
        
            
       
    cc.director.loadScene("chooseui",()=>{
       let a=new SHMessage("CH",0,0,1,"To")
        MessageCenter.SendMessage(a);
    
})

} 

static send(sh:GMessage){

let a=[KHD2.ln+1 ,sh,"1"]
let b=JSON.stringify(a)
const data = {
    id:5,
    error:12,
    gamemessage:b
  
  };


KHD2.socket.send(JSON.stringify(data))
KHD2.ln++;
}







static redtos(data){

switch (data.error) {
    case 11: 
    cc.find("Canvas/fangJian/p1").getComponent(YP).PauseAudioclip("byp",1)
    
    
    cc.director.loadScene("chooseui",()=>{
        let a=new SHMessage("CH",0,0,1,"To")
         MessageCenter.SendMessage(a);
        
         cc.find("Canvas").getComponent(YP).stopAllAudio()
                 cc.find("Canvas").getComponent(YP).PlayAudioclip("byp",true,2)
        
        })

        
        break;
        case 12:cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("不在房间内");
        
        break;
        case 13:cc.find("Canvas/CHU").children[2].getComponent(DTTS).WZTS("你不是房主");
        
        break;

    default:
        break;
}



}


static BGload(K){
    console.log(K)
    cc.find("Canvas").getComponent(YP).stopAllAudio()
    cc.find("Canvas").getComponent(YP).PlayAudioclip("byp",true,3)
    if(K.valuesum==6&&KHD2.PT.includes(1)){
 MessageCenter.MakeSHMessage("AM",[0],0,0,"CX");
 console.log(K)
}}


static GM(data){


    let c=JSON.parse(data.gamemessage);
        
    KHD2.JMessage.push(c)
    for(let v of KHD2.JMessage){
       if(v[0]==KHD2.dn+1){
        
        KHD2.dn++
    
    let a=new GMessage(v[1].Type,v[1].Command,v[1].Content,v[1].from,v[1].SHtype)
    
    console.log(data)
    MessageCenter.SendMessage(a)
        KHD2.JMessage.splice(KHD2.JMessage.indexOf(v),1);
       } 
    
    }
    
    
    KHD2.ln=KHD2.dn;
    




}

static FJG(data){

    cc.director.loadScene("thi",()=>{

        cc.find("Canvas/fangJian/kaishi").active=false
        document.body.style.cursor = ' auto';  }
    

    
    
    )




}



static GFJ(data){
KHD2.PT=[0]
KHD2.FZ=false
KHD2.FJN=false

}

}
